/**
 * The single player mode package of the application.
 */
package fr.umlv.m2.android.quizz.singleplayer;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import fr.umlv.m2.android.quizz.HomepageActivity;
import fr.umlv.m2.android.quizz.R;
import fr.umlv.m2.android.quizz.database.Answer;
import fr.umlv.m2.android.quizz.database.AnswerDb;
import fr.umlv.m2.android.quizz.database.Level;
import fr.umlv.m2.android.quizz.database.LevelDb;
import fr.umlv.m2.android.quizz.database.Question;
import fr.umlv.m2.android.quizz.database.QuestionDb;

/**
 * This class defines the question of single player mode activity.
 * 
 * @author Gambouele Bertrand.
 * @author Viravout Alexandre.
 */
public class SinglePlayerQuestionActivity extends Activity {
	/**
	 * The single player question title.
	 */
	private TextView title;
	/**
	 * The single player question activity question.
	 */
	private TextView question;
	/**
	 * The single player question activity answer 1.
	 */
	private Button answer1;
	/**
	 * The single player question activity answer 2.
	 */
	private Button answer2;
	/**
	 * The single player question activity answer 3.
	 */
	private Button answer3;
	
	/**
	 * The single player question activity intent.
	 */
	private Intent intent;
	/**
	 * The single player activity bundle.
	 */
	private Bundle bundle;
	/**
	 * The user id.
	 */
	private long userId;
	/**
	 * The level id.
	 */
	private long levelId;
	/**
	 * The theme id.
	 */
	private long themeId;
	/**
	 * The old question already displayed.
	 */
	private long[] oldQuestions;
	
	/**
	 * The current question number.
	 */
	private int currentQuestionNumber;
	/**
	 * The current number of good answer.
	 */
	private int goodAnswer;
	/**
	 * The current number of bad answer.
	 */
	private int badAnswer;
	/**
	 * The current time.
	 */
	private long time;
	
	/**
	 * The good answer button id.
	 */
	private int goodAnswerButtonId;
	
	/**
	 * The audio manager.
	 */
	private AudioManager audio;
	
	/**
	 * The current chronometer.
	 */
	private Chronometer chronometer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.single_player_question);
		
		this.audio = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
		this.chronometer = (Chronometer)findViewById(R.id.singlePlayerQuestionChronometer);
		
		this.intent = this.getIntent();
		this.bundle = this.intent.getExtras();
		this.userId = this.bundle.getLong("userId");
		this.levelId = this.bundle.getLong("levelId");
		this.themeId = this.bundle.getLong("themeId");
		this.oldQuestions = this.bundle.getLongArray("oldQuestions");
		
		this.currentQuestionNumber = this.bundle.getInt("currentQuestionNumber");
		this.goodAnswer = this.bundle.getInt("goodAnswer");
		this.badAnswer = this.bundle.getInt("badAnswer");
		this.time = this.bundle.getLong("time");
		System.out.println(this.time);
		if(this.time != 0) {
			this.chronometer.setBase(SystemClock.elapsedRealtime() - this.time);
		} else {
			this.chronometer.setBase(SystemClock.elapsedRealtime());
		}
		this.chronometer.start();
		this.showElapsedTime();
		
		this.title = (TextView)findViewById(R.id.singlePlayerQuestionTitle);
		this.title.setText(
				this.getResources().getString(R.string.singlePlayerQuestionTitle) +
				" " +
				this.currentQuestionNumber		
		);
		this.currentQuestionNumber += 1;
		
		this.question = (TextView)findViewById(R.id.singlePlayerQuestionText);
		this.answer1 = (Button)findViewById(R.id.singlePlayerQuestionAnswerButton1);
		this.answer2 = (Button)findViewById(R.id.singlePlayerQuestionAnswerButton2);
		this.answer3 = (Button)findViewById(R.id.singlePlayerQuestionAnswerButton3);
		
		
		LevelDb levelDb = new LevelDb(this);
		levelDb.open();
		Level level = levelDb.getLevelWithId(this.levelId);
		levelDb.close();
		
		this.intent = new Intent(this, SinglePlayerQuestionActivity.class);
		if(this.currentQuestionNumber > level.getNbQuestion()) {
			this.intent = new Intent(this, SinglePlayerResultActivity.class);
		}
				
		QuestionDb questionDb = new QuestionDb(this);
		questionDb.open();
		List<Question> questions = questionDb.getQuestionsWithLevelAndTheme(this.levelId, this.themeId);
		questionDb.close();
		
		final List<Question> tmp = new ArrayList<Question>();
		for(Question question : questions) {
			for(long id : this.oldQuestions) {
				if(question.getId() != id) {
					tmp.add(question);
				}
			}
		}
		questions = tmp;
		
		final Random rand = new Random();
		final int questionIndex = rand.nextInt(questions.size());
		Question question = questions.get(questionIndex);
		this.oldQuestions[(this.currentQuestionNumber-2)] = question.getId();
		
		this.question.setText(question.getQuestionText());
		
		AnswerDb answerDb = new AnswerDb(this);
		answerDb.open();
		List<Answer> answers = answerDb.getAnswersWithQuestionAndTheme(question.getId(), themeId);
		answerDb.close();
		
		final long goodAnswerId = answers.get(0).getId();
		
		int answerIndex = rand.nextInt(answers.size());
		Answer answer = answers.get(answerIndex);
		answers.remove(answer);
		this.answer1.setText(answer.getAnswerText());
		if(answer.getId() == goodAnswerId) {
			this.goodAnswerButtonId = this.answer1.getId();
		}
		
		answerIndex = rand.nextInt(answers.size());
		answer = answers.get(answerIndex);
		answers.remove(answer);
		this.answer2.setText(answer.getAnswerText());
		if(answer.getId() == goodAnswerId) {
			this.goodAnswerButtonId = this.answer2.getId();
		}
		
		answer = answers.get(0);
		this.answer3.setText(answer.getAnswerText());
		if(answer.getId() == goodAnswerId) {
			this.goodAnswerButtonId = this.answer3.getId();
		}
		
		this.answer1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				updateGameScore(v.getId());
				nextQuestion();
			}
		});
		
		this.answer2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				updateGameScore(v.getId());
				nextQuestion();
			}
		});

		this.answer3.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {				
				updateGameScore(v.getId());
				nextQuestion();
			}
		});
	}
	
	private void updateGameScore(int buttonId) {
		if(this.audio.getRingerMode() == AudioManager.RINGER_MODE_NORMAL) {
			if(this.goodAnswerButtonId == buttonId) {
				MediaPlayer.create(this, R.raw.good_answer).start();
			} else {
				MediaPlayer.create(this, R.raw.surprise).start();
			}
		}
		
		if(this.goodAnswerButtonId == buttonId) {
			this.goodAnswer += 1;
		} else {
			this.badAnswer += 1;
			Button badButton = (Button)findViewById(buttonId);
			badButton.setTypeface(null, Typeface.BOLD);
			badButton.setTextSize(20);
			badButton.setTextColor(this.getResources().getColor(R.color.badAnswer));
		}
		
		Button goodButton = (Button)findViewById(this.goodAnswerButtonId);
		goodButton.setTypeface(null, Typeface.BOLD);
		goodButton.setTextSize(20);
		goodButton.setTextColor(this.getResources().getColor(R.color.goodAnswer));
	}
	
	private void nextQuestion() {		
		this.intent.putExtra("currentQuestionNumber", this.currentQuestionNumber);
		this.intent.putExtra("goodAnswer", this.goodAnswer);
		this.intent.putExtra("badAnswer", this.badAnswer);
		this.intent.putExtra("time", showElapsedTime());
		
		this.intent.putExtra("userId", this.userId);
		this.intent.putExtra("levelId", this.levelId);
		this.intent.putExtra("themeId", this.themeId);
		this.intent.putExtra("oldQuestions", this.oldQuestions);
		startActivity(this.intent);
	}
	
	@Override
	public void onBackPressed() {		
		LayoutInflater factory = LayoutInflater.from(SinglePlayerQuestionActivity.this);
		final View backHomepageDialogView = factory.inflate(R.layout.back_homepage_dialog, null);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(SinglePlayerQuestionActivity.this);
		builder.setView(backHomepageDialogView);
		builder.setTitle(R.string.backHomepageDialogTitleText);
		
		builder.setPositiveButton(R.string.backHomepageDialogValidateButton, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				intent = new Intent(SinglePlayerQuestionActivity.this, HomepageActivity.class);
				intent.putExtra("userId", userId);
				startActivity(intent);
			}
		});
		
		builder.setNegativeButton(R.string.dialogCancelButton, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {}
		});
		
		builder.show();
	}
	
	private long showElapsedTime() {
		long elapsedMillis = SystemClock.elapsedRealtime() - this.chronometer.getBase();
		return elapsedMillis;
	}
}
